package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.dto.OrderSettingDto;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import com.itheima.vto.OrderSettingVto;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/ordersetting")
public class ordersettingController {
    @Autowired
    private OrdersettingService ordersettingService;

    /**
     * 获取模板
     * @param filename
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]>  download(@RequestParam String filename){
        log.info("文件名:{}", filename);

        try (XSSFWorkbook excel = new XSSFWorkbook()) {
            XSSFSheet sheet = excel.createSheet("Sheet1");
            XSSFRow row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue("日期");
            row1.createCell(1).setCellValue("人数");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            excel.write(baos);
            byte[] excelBytes = baos.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" + filename);

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据日期修改可预约人数
     * @param orderSettingDto
     * @return
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSettingDto orderSettingDto) throws ParseException {
        log.info("修改预约设置：{}",orderSettingDto);
        boolean temp = ordersettingService.editNumberByOrderDate(orderSettingDto);
        return new Result(temp,temp? MessageConstant.ORDERSETTING_SUCCESS:MessageConstant.ORDERSETTING_FAIL);
    }


    /**
     * 根据年月查询对应的预约设置信息
     * @param month
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam String month){
        // 解析年月
        String[] parts = month.split("-");
        int year = Integer.parseInt(parts[0]);
        int monthNumber = Integer.parseInt(parts[1]);
        List<OrderSettingVto>  list=  ordersettingService.getOrderSettingByMonth(year,monthNumber);
        return new Result(list!=null?true:false,list!=null?MessageConstant.GET_ORDERSETTING_SUCCESS:MessageConstant.GET_ORDERSETTING_FAIL,list);

    }

    /**
     * 文件上传（Excel）,并获取其中数据存入数据库中
     * @param excelFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload( MultipartFile excelFile){
        List<OrderSettingDto> list = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        try {
            POIUtils.checkFile(excelFile);
            Workbook workbook =POIUtils.getWorkBook(excelFile);
            Sheet sheet = workbook.getSheetAt(0);
            for(Row row:sheet){
                if(row.getRowNum()==0) continue;
                OrderSettingDto orderSettingDto = new OrderSettingDto();
//                System.out.println(row.getCell(0).getNumericCellValue());
                Date date = row.getCell(0).getDateCellValue();
                orderSettingDto.setOrderDate(date.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate());
                orderSettingDto.setNumber((int) row.getCell(1).getNumericCellValue());
                list.add(orderSettingDto);
            }
            ordersettingService.addData(list);



        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(true,MessageConstant.UPLOAD_SUCCESS);
    }
}
